package top.dimples.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.util.StringUtils;

public class ObjectMapperUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将任意对象转化为JSON
     */
    public static String toJSON(Object object) {
        try {
            if (object == null) {
                throw new RuntimeException("传递的参数object为null,请认真检查");
            }
            MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("传递的对象不支持json转化/检查是否有get/set方法");
        }
    }


    public static <T> T toObject(String json, Class<T> target) {

        if (StringUtils.isEmpty(json) || target == null) {
            throw new RuntimeException("传递的参数不能为null");
        }
        try {
            MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
            return MAPPER.readValue(json, target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("json转化异常");
        }
    }
}


